package com.jsb.laundry.common.utils.job;

import com.alibaba.fastjson.JSONObject;
import com.jsb.laundry.common.config.properties.WechatMiniPayProperties;
import com.jsb.laundry.common.utils.http.HttpUtil;
import com.jsb.laundry.common.utils.redis.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

@Service
@EnableScheduling
public class WechatAccessToken {

    private static final Logger LOGGER = LoggerFactory.getLogger(WechatAccessToken.class);

    private static RedisUtil redisUtil;
    private static WechatMiniPayProperties wechatMiniPayProperties;

    public WechatAccessToken(RedisUtil redisUtil, WechatMiniPayProperties wechatMiniPayProperties) {
        WechatAccessToken.redisUtil = redisUtil;
        WechatAccessToken.wechatMiniPayProperties = wechatMiniPayProperties;
    }

    @PostConstruct
    public void init() {
//        getAccessToken();
    }

    private final long fix = 1000 * 60 * 5;

//    @Async("myAsync")
//    @Scheduled(fixedRate = fix) //每1小时执行一次
//    @Scheduled(cron = "0 0 */1 * * ?") //每1小时执行一次
    public void testScheduleTask() {
        getAccessToken();
    }


    public static String getAccessToken() {
        /**
         * 获取access_token
         */
        String accessTokenUrl = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", wechatMiniPayProperties.getAppId(), wechatMiniPayProperties.getAppSecret());
        String s1 = HttpUtil.sendGet(accessTokenUrl, null, null, null);
        JSONObject jsonObject2 = JSONObject.parseObject(s1);
        String access_tokens = jsonObject2.getString("access_token");
        redisUtil.setCacheObject("wx_user_access_token", access_tokens, 1, TimeUnit.HOURS); //1小时过期
        LOGGER.info("获取微信access_token:{}",access_tokens);
        return access_tokens;
    }

}
